﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using vuonthieunhi.Library;

namespace vuonthieunhi.Models
{
    public class PartnerDao:BaseDao
    {
        public List<GetHotPartnerResult> GetHotPartner()
        {
            return dbContext.GetHotPartner().ToList();
        }

        public List<GetViewPartnerResult> GetHotViewPartner()
        {
            return dbContext.GetViewPartner().ToList();
        }

        public void UpdateView(Partner objUI)
        {
            Partner objDb = GetByID(objUI.ID);
            if (objDb != null)
            {
                objDb.Views = objUI.Views;
                dbContext.SubmitChanges();
            }
        }

        public List<GetNewPartnerResult> GetNewPartner()
        {
            return dbContext.GetNewPartner().ToList();
        }

        public void  listPromotion(int category,int number)
        {
           List<Partner> list = dbContext.Partners.Where(q=> q.Category.ParentId.Value == category && !q.DeleteFlag).ToList();
           //List<Partner> list = dbContext.Partners.Where(q => q.CategoryID == category && !q.DeleteFlag).ToList();
           foreach (Partner item in list)
           {
               Partner objdb = GetByID(item.ID);
               objdb.OldPrice = item.CurrentPrice.Value;
               objdb.CurrentPrice = Math.Round((item.CurrentPrice.Value - ((item.CurrentPrice.Value * number / 100))), 1);
               //objdb.CurrentPrice = Math.Round((item.CurrentPrice.Value - (item.CurrentPrice.Value * number / 100)), 1);
              // objdb.OldPrice = item.CurrentPrice.Value;

               dbContext.SubmitChanges();
           }
        }

        public List<GetSalesPartnerResult> GetSalesPartner()
        {
            return dbContext.GetSalesPartner().ToList();
        }

        public List<sp_GetPartnerResult> GetPartner(string name,int categoryID)
        {
            return dbContext.sp_GetPartner(name, categoryID).ToList();
        }

        public Partner GetByAlias(string alias)
        {
            return dbContext.Partners.Where(q => q.Alias.Equals(alias)).FirstOrDefault();
        }

        public Partner GetByID(int id)
        {
            return dbContext.Partners.Where(q => q.ID.Equals(id)).FirstOrDefault();
        }

        public List<sp_GetGlobalSearchResult> GetAdvanceSearch(string name, int category, int manufacturer, double from, double to)
        {
            return dbContext.sp_GetGlobalSearch(name, category, manufacturer, from, to).ToList();
        }

        public List<sp_GetPartnerListResult> GetList(string text,int category)
        {
            return dbContext.sp_GetPartnerList(text, category).ToList();
        }

        private bool CheckUniqueAlias(Partner objUI,bool isCreate)
        {
            Partner objDB = null;
            if(isCreate)
            {
                objDB = dbContext.Partners.Where(q => q.Alias.Equals(objUI.Alias)).FirstOrDefault();
            }
            else
            {
                objDB = dbContext.Partners.Where(q => q.ID != objUI.ID && q.Alias.Equals(objUI.Alias) ).FirstOrDefault();
            }
            if (objDB != null)
            {
                return false;
            }
            return true;
        }

        public Message Update(Partner objUI)
        {
            Message msg = null;
            try
            {
                Partner objDb = GetByID(objUI.ID);
                if (objDb != null)
                {
                    if (CheckUniqueAlias(objUI,false))
                    {
                        objDb.Logo = objUI.Logo;
                        objDb.CategoryID = objUI.CategoryID;
                        objDb.PartnerName = objUI.PartnerName;
                        objDb.Description = objUI.Description;
                        objDb.PartnerOrder = objUI.PartnerOrder;
                        objDb.DeleteFlag = objUI.DeleteFlag;
                        objDb.OldPrice = objUI.OldPrice;
                        objDb.CurrentPrice = objUI.CurrentPrice;
                        objDb.Views = objUI.Views;
                        objDb.Status = objUI.Status;
                        objDb.CodeID = objUI.CodeID;
                        objDb.Store = objUI.Store;
                        objDb.Alias = objUI.Alias;
                        objDb.IsHotSales = objUI.IsHotSales;
                        objDb.IsNew = objUI.IsNew;
                        objDb.BigImages = objUI.BigImages;
                        objDb.ManufacturerID = objUI.ManufacturerID;
                        objDb.Age = objUI.Age;
                        objDb.Dimension = objUI.Dimension;
                        objDb.Color = objUI.Color;
                        objDb.SubName = objUI.SubName;
                        dbContext.SubmitChanges();

                        // Show success message
                        msg = new Message(MessageConstants.I0001, MessageType.Info, "Ðối tác '" + objUI.PartnerName + "'", "cập nhật");
                    }
                    else
                    {
                        msg = new Message(MessageConstants.E0002, MessageType.Error, "Ðối tác '" + objUI.PartnerName + "'", "đã tồn tại");
                    }
                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        /// <summary>
        /// Insert a question without answer
        /// </summary>
        /// <param name="question"></param>
        /// <returns>int</returns>
        public Message Insert(Partner partner)
        {
            Message msg = null;
                if (partner != null)
                {
                    if (CheckUniqueAlias(partner,true))
                    {
                        dbContext.Partners.InsertOnSubmit(partner);
                        //Submit changes to database
                        dbContext.SubmitChanges();
                        msg = new Message(MessageConstants.I0001, MessageType.Info, "nhập", "sản phẩm");
                    }
                    else
                    {
                        msg = new Message(MessageConstants.E0002, MessageType.Error, "Ðối tác '" + partner.PartnerName + "'", "đã tồn tại");
                    }
                }
                return msg;
        }

        public Message UpdateLogoImage(Partner objUI)
        {
            Message msg = null;
            try
            {
                if (objUI != null)
                {
                    Partner objDb = GetByID(objUI.ID);

                    if (objDb != null)
                    {
                        objDb.Logo = objUI.Logo;
                        dbContext.SubmitChanges();

                        msg = new Message(MessageConstants.I0001, MessageType.Info, "logo đối tác", "cập nhật");

                    }
                }
            }
            catch
            {
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        public Message UpdateBigImage(Partner objUI)
        {
            Message msg = null;
            try
            {
                if (objUI != null)
                {
                    Partner objDb = GetByID(objUI.ID);

                    if (objDb != null)
                    {
                        objDb.BigImages = objUI.BigImages;
                        dbContext.SubmitChanges();

                        msg = new Message(MessageConstants.I0001, MessageType.Info, "logo đối tác", "cập nhật");

                    }
                }
            }
            catch
            {
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        /// <summary>
        /// DeleteList
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Message DeleteList(string ids)
        {
            Message msg = null;
            try
            {
                if (!string.IsNullOrEmpty(ids))
                {
                    bool canDelete = true;
                    ids = ids.TrimEnd(',');
                    int collaboratorID = 0;

                    List<string> imageList = new List<string>();
                    string[] idArr = ids.Split(',');
                    int total = idArr.Count();
                    foreach (string id in idArr)
                    {
                        bool isValid = Int32.TryParse(id, out collaboratorID);
                        Partner partner = GetByID(collaboratorID);
                        if (partner != null)
                        {
                            bool isSuccess = Delete(partner);
                            imageList.Add(partner.Logo);
                            if (!isSuccess)
                            {
                                canDelete = false;
                                // Show succes message
                                msg = new Message(MessageConstants.E0006, MessageType.Error, "xóa", "đối tác này");
                                break;
                            }
                        }
                        else
                        {
                            total--;
                        }
                    }

                    if (canDelete)
                    {
                        // Show succes message
                        msg = new Message(MessageConstants.I0001, MessageType.Info, total.ToString() + " đối tác", "xóa");
                        //Delete image
                        foreach (string img in imageList)
                        {
                            if (!string.IsNullOrEmpty(img) && img != Constants.NO_IMAGE)
                            {
                                string strPath = HttpContext.Current.Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER) + img;
                                //strPath += "\\" + image;
                                if (System.IO.File.Exists(strPath))
                                    System.IO.File.Delete(strPath);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        /// <summary>
        /// Delete
        /// </summary>
        /// <param name="objUI"></param>
        private bool Delete(Partner objUI)
        {
            bool result = true;
            if (objUI != null)
            {
                // Get current group in dbContext
                Partner objDb = GetByID(objUI.ID);
                if (objDb != null)
                {
                    // Set delete info                    
                    objDb.DeleteFlag = true;
                    // Submit changes to dbContext
                    dbContext.SubmitChanges();
                }
                else
                {
                    result = false;
                }
            }
            return result;
        }


        public Message UpdateHotSales(int id)
        {
            Message msg = null;
            try
            {

                // Get current group in dbContext
                Partner objDb = GetByID(id);

                if (objDb != null)
                {
                    // Update info by objUI
                    if (objDb.IsHotSales)
                    {
                        objDb.IsHotSales = false;
                    }
                    else
                    {
                        objDb.IsHotSales = true;
                    }
                    // Submit changes to dbContext
                    dbContext.SubmitChanges();
                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Đối tác " + objDb.PartnerName, "cập nhật");


                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }

            return msg;
        }

        public Message UpdateStatusNew(int id)
        {
            Message msg = null;
            try
            {

                // Get current group in dbContext
                Partner objDb = GetByID(id);

                if (objDb != null)
                {
                    // Updatinfo by objUI
                    if (objDb.IsNew)
                    {
                        objDb.IsNew = false;
                    }
                    else
                    {
                        objDb.IsNew = true;
                    }
                    // Submit changes to dbContext
                    dbContext.SubmitChanges();
                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Đối tác " + objDb.PartnerName, "cập nhật");


                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }

            return msg;
        }

        public Message UpdateStatusActive(int id)
        {
            Message msg = null;
            try
            {

                // Get current group in dbContext
                Partner objDb = GetByID(id);

                if (objDb != null)
                {
                    // Updatinfo by objUI
                    if (objDb.DeleteFlag)
                    {
                        objDb.DeleteFlag = false;
                    }
                    else
                    {
                        objDb.DeleteFlag = true;
                    }
                    // Submit changes to dbContext
                    dbContext.SubmitChanges();
                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Đối tác " + objDb.PartnerName, "cập nhật");


                }
            }
            catch (Exception)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }

            return msg;
        }

    }
}